﻿using MediatR;
using Medical.Api.Write.Application.Command.RecyclingCleaning;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 修改登记清洗状态命令处理
    /// </summary>
    public class UpdateCleaningCompletedCommandHandlter : IRequestHandler<UpdateCleaningCompletedCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CleaningRegistration> _cleaningRegistrationRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cleaningRegistrationRepository">清洗登记仓储</param>
        public UpdateCleaningCompletedCommandHandlter(IBaseRepository<CleaningRegistration> cleaningRegistrationRepository)
        {
            _cleaningRegistrationRepository = cleaningRegistrationRepository;
        }

        /// <summary>
        /// 处理命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateCleaningCompletedCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据Id查询待清洗状态的登记清洗信息
                var cleaningRegistration = _cleaningRegistrationRepository.GetAll().FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted && x.CleaningState == RecoveryStatusEnum.待清洗);

                // 验证记录是否存在
                if (cleaningRegistration == null)
                {
                    return new ApiResult<int> { Code = ApiEnums.Error, Msg = "清洗登记记录不存在" };
                }

                //  完成时间
                cleaningRegistration.FinishTime = request.FinishTime;
                //清洗结果等字段
                cleaningRegistration.CleaningResult = request.CleaningResult;
                //清洗时长
                cleaningRegistration.CleaningDuration = Convert.ToInt32((request.FinishTime - cleaningRegistration.StartTime).TotalMinutes);
                //更新完成人
                cleaningRegistration.FinishPerson = request.FinishPerson;
                //  将清洗状态更改为已完成
                cleaningRegistration.CleaningState = RecoveryStatusEnum.已完成;

                // 更新数据库
                var result = _cleaningRegistrationRepository.Update(cleaningRegistration);

                if (result > 0)
                {
                    return new ApiResult<int> { Code = ApiEnums.Success, Msg = "更新清洗状态成功", Data = result };
                }
                else
                {
                    return new ApiResult<int> { Code = ApiEnums.Error, Msg = "更新清洗状态失败" };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int> { Code = ApiEnums.Error, Msg = $"更新清洗状态异常：{ex.Message}" };
            }
        }
    }
}
